package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.Set;

@Controller
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    //根据用户名查询数据库
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查找用户
        User user = userService.findByUsername(username);
        if (user == null) {
            return null;
        }

        ArrayList<GrantedAuthority> list = new ArrayList<>();
        //根据用户查找角色
        Set<Role> roles = user.getRoles();
        if (roles!=null){
            for (Role role : roles) {
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                //根据角色查找权限
                Set<Permission> permissions=role.getPermissions();
                if (permissions!=null){
                    for (Permission permission : permissions) {
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        //返回用户名和密码和权限
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(),list );
    }
}
